package com.zoe.onelink.core.web.jackson.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleSerializers;
import com.zoe.onelink.common.enumeration.BaseEnum;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-04-22
 */
public class JacksonEnumSimpleSerializers extends SimpleSerializers {

    @Override
    public JsonSerializer<?> findSerializer(SerializationConfig config, JavaType type, BeanDescription beanDesc) {
        if (type.isEnumType()) {
            return new CustomEnumSerializer();
        }
        return super.findSerializer(config, type, beanDesc);
    }

    @JsonComponent
    public static class CustomEnumSerializer extends JsonSerializer<BaseEnum<Serializable>> {

        @Override
        public void serialize(BaseEnum value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            if (value == null) {
                gen.writeNull();
                return;
            }
            JsonStreamContext outputContext = gen.getOutputContext();
            Serializable code = value.getCode();
            String desc = value.getDesc();
            gen.writeObject(code);
            Object currentValue = outputContext.getCurrentValue();
            if (currentValue instanceof List) {
                gen.writeArrayFieldStart("desc");
                gen.writeStartArray(5);
                gen.setCurrentValue(desc);
                gen.writeEndArray();
            } else {
                // 翻译字段
                gen.writeObjectField(outputContext.getCurrentName() + "Desc", desc);
            }

        }

    }

}
